package com.danger.Model.threads;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.widget.ImageView;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * Created by danger on 2016/3/31.
 */
public class MyBitmapThread extends Thread {

    private ImageView imageView;
    private String url;
    private Handler handler;
    private Bitmap bitmap;

    public MyBitmapThread(ImageView imageView, String url, Handler handler) {
        this.imageView = imageView;
        this.url = url;
        this.handler = handler;
    }

    @Override
    public void run() {
        try {
            URL httpUrl = new URL(url);
            // 通过url连接获取内容
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
            // 设置响应时间
            conn.setReadTimeout(5000);
            // 设置请求方式
            conn.setRequestMethod("GET");
            // 获取HttpURLConnection的输入流
            InputStream in = conn.getInputStream();
            // 将获取到的输入流转化为bitmap
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = false;
            options.inSampleSize = 10;   //width，hight设为原来的十分一
            bitmap = BitmapFactory.decodeStream(in, null, options);
            conn.disconnect();
            handler.post(new Runnable() {
                @Override
                public void run() {
                    imageView.setAdjustViewBounds(true);
                    imageView.setImageBitmap(bitmap);
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
